import Vue from 'vue';
import Vuex from 'vuex';
import createPersistedState from "vuex-persistedstate";

Vue.use(Vuex)

export default new Vuex.Store({
  plugins:[createPersistedState()],
  state: {
    todos: JSON.parse(localStorage.getItem("vuex") || '[]'),
    activeTab: "all",
  },
  getters: {
    activeTab: function (state) {
      return state.activeTab;
    },
    //剩下的项目
    remainging: function (state) {
      let remaingingTodos = state.todos.filter(v => {
        // return !v.status //false => 返回
        if (!v.status) {
          return true;
        }
      });
      return remaingingTodos.length;
    },
    //过滤后的todos
    allChecked: function (state) {
      let checked = true;
      //只要todos 里面有一个 status false => allChecked = false
      state.todos.map((v) => {
        if (!v.status) checked = false;
      });
      return checked;
    },
    filterTodos: function (state) {
      // all active completed
      if (state.activeTab === "all") {
        return state.todos;
      } else if (state.activeTab === "active") {
        return state.todos.filter(v => {
          //v.status => false
          return !v.status;
        });
      } else if (state.activeTab === "completed") {
        return state.todos.filter(v => {
          //v.status => true
          return v.status;
        });
      }
    }
  },
  mutations: {
    handleClearCompleted: function (state) {
      //筛选出未完成 => todos
      let activeTodos = state.todos.filter((v) => {
        //v.status => false
        return !v.status; //false => !false = true
      });
      state.todos = activeTodos;
    },
    changeActiveTab: function (state, { payload }) {
      state.activeTab = payload.activeTab;
    },
    deletTodo: function (state, { payload }) {
      state.todos.splice(payload.index, 1);
    },
    addTodo: function (state, { payload }) {
      state.todos.push(payload);
    },
    //全选逻辑
    allCheck: function (state) {
      state.todos.map((v) => {
        v.status = true;
      });
    }
  },
  actions: {
  },
  modules: {
  }
})
